<template>
	<comRoot>
		<template #page>
			<comDetailNavigateBack :title="commonNavTitle + message" />

			<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :style="{
					width: '100vw',
					height: '100vh',
				}" :src="`${commonConfigs.domainFrontFileLink}/files/images/demo/demo-bg.jpeg`" class="bg" />

			<view class="demo-page flex-all-center">
				<view id="container" ref="box" :style="{width: box_w + 'rpx', height: box_h + 'rpx'}">
					<view v-for="(row, i) in rows" :key="i">
						<view class="cell" v-for="(col, j) in row" :key="j" :style="{
								left: col.x * el_w + 'rpx', 
								top: col.y * el_h + 'rpx', 
								width: el_w + 'rpx', 
								height: el_h + 'rpx',
								borderTop: col.borderTop,
								borderLeft: col.borderLeft,
								background: col.background,
							}" @click="clickFn(col)" :id="`${col.x}_${col.y}`" :ref="`${col.x}_${col.y}`">
							<!-- <span class="text-nowrap">{{col.x}},{{col.y}}</span> -->
						</view>
						
						<image v-if="commonConfigs && commonConfigs.domainFrontFileLink && startVector.length" :style="{
								width: '50rpx',
								height: '50rpx',
								left: startVector[0] * el_w + 'rpx',
								top: startVector[1] * el_h + 'rpx',
								transition: `all ${path * 0.2}s`,
							}" :src="`${commonConfigs.domainFrontFileLink}/files/images/demo/monkey.png`" class="bg" />
					</view>
				</view>
			</view>
		</template>
	</comRoot>
</template>

<script>
	import APlus from './APlus.js';
	import { setAsyncFunWait } from '@/setupproject/TOOLS_FUN';
	export default {
		data() {
			return {
				commonNavTitle: '大逃杀',
				box_w: 750,
				box_h: 500,
				// el_w: 50,
				// el_h: 50,
				obstacles: [],
				startVector: [],
				endVector: [],
				clickCount: 0,
				message: '',
				rows: [],
				path: [],
				obstacles: [
					[0, 6],
					[1, 6],
					[2, 6],
					[3, 6],
					[4, 6],
					[5, 6],
					[5, 7],
					[5, 8],
					[5, 9],
					[5, 10],
					[5, 11],
					[5, 12],
					[0, 12],
					[1, 12],
					[2, 12],
					[3, 12],
					[6, 8],
					[7, 8],
					[7, 7],
					[8, 7],
					[9, 7],
					[10, 7],
					[11, 7],
					[12, 7],
					[12, 6],
					[13, 6],
					[14, 6],
					[9, 7],
					[9, 8],
					[9, 9],
					[9, 10],
					[9, 11],
					[9, 12],
					[7, 12],
					[8, 12],
					[12, 12],
					[13, 12],
					[14, 12],
					[12, 14],
					[13, 14],
					[14, 14],
					[12, 15],
					[12, 16],
					[12, 17],
					[12, 18],
					[12, 20],
					[13, 20],
					[14, 20],
					[3, 14],
					[3, 15],
					[3, 16],
					[3, 17],
					[3, 18],
					[0, 18],
					[1, 18],
					[2, 18],
					[3, 20],
					[3, 21],
					[3, 22],
					[3, 23],
					[0, 23],
					[1, 23],
					[2, 23],
					[4, 14],
					[5, 14],
					[6, 14],
					[7, 14],
					[8, 14],
					[9, 14],
					[9, 15],
					[9, 16],
					[9, 17],
					[9, 18],
					[4, 18],
					[5, 18],
					[8, 18],
					[9, 20],
					[9, 21],
					[9, 22],
					[9, 23],
					[4, 23],
					[5, 23],
					[6, 23],
					[7, 23],
					[8, 23],
					[4, 20],
					[5, 20],
					[6, 20],
					[13, 23],
					[14, 23],
					[1, 1],
				],
				boxData: {
					'杂物间': [
						[0, 7],
						[1, 7],
						[2, 7],
						[3, 7],
						[4, 7],
						[0, 8],
						[1, 8],
						[2, 8],
						[3, 8],
						[4, 8],
						[0, 9],
						[1, 9],
						[2, 9],
						[3, 9],
						[4, 9],
						[0, 10],
						[1, 10],
						[2, 10],
						[3, 10],
						[4, 10],
						[0, 11],
						[1, 11],
						[2, 11],
						[3, 11],
						[4, 11],
					],
					'休息室': [
						[8, 8],
						[6, 9],
						[7, 9],
						[8, 9],
						[6, 10],
						[7, 10],
						[8, 10],
						[6, 11],
						[7, 12],
						[8, 13],
					],
					'厂长室': [
						[13, 7],
						[14, 7],
						[10, 8],
						[11, 8],
						[12, 8],
						[13, 8],
						[14, 8],
						[10, 9],
						[11, 9],
						[12, 9],
						[13, 9],
						[14, 9],
						[10, 10],
						[11, 10],
						[12, 10],
						[13, 10],
						[14, 10],
						[10, 11],
						[11, 11],
						[12, 11],
						[13, 11],
						[14, 11],
					],
					'谈话室': [
						[0, 13],
						[1, 13],
						[2, 13],
						[0, 14],
						[1, 14],
						[2, 14],
						[0, 15],
						[1, 15],
						[2, 15],
						[0, 16],
						[1, 16],
						[2, 16],
						[0, 17],
						[1, 17],
						[2, 17],
					],
					'洗衣房': [
						[4, 15],
						[5, 15],
						[6, 15],
						[7, 15],
						[8, 15],
						[4, 16],
						[5, 16],
						[6, 16],
						[7, 16],
						[8, 16],
						[4, 17],
						[5, 17],
						[6, 17],
						[7, 17],
						[8, 17],
					],
					'工作室': [
						[13, 15],
						[14, 15],
						[13, 16],
						[14, 16],
						[13, 17],
						[14, 17],
						[13, 18],
						[14, 18],
						[13, 19],
						[14, 19],
					],
					'茶水间': [
						[0, 19],
						[1, 19],
						[2, 19],
						[0, 20],
						[1, 20],
						[2, 20],
						[0, 21],
						[1, 21],
						[2, 21],
						[0, 22],
						[1, 22],
						[2, 22],
					],
					'音乐室': [
						[4, 21],
						[5, 21],
						[6, 21],
						[7, 21],
						[8, 21],
						[4, 22],
						[5, 22],
						[6, 22],
						[7, 22],
						[8, 22],
					],
				},
				
			};
		},
		computed: {
			el_w() {
				return 50;
				// return Math.floor(this.box_w / 15);
			},
			el_h() {
				return 50;
				// return Math.floor(this.box_h / this.el_h);
			},
			col() {
				return Math.floor(this.box_w / this.el_w);
			},
			row() {
				return Math.floor(this.box_h / this.el_h);
			},
			commonNavHeight() {
				return this.$store.getters.commonNavHeight + 'px';
			},
			commonConfigs() {
				return this.$store.getters.commonConfigs || {};
			},
			commonOnline() {
				return this.$store.getters.commonOnline;
			},
		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					// *****高度宽度的单位都是px 
					console.log(res.screenHeight); // 屏幕高度，包含导航栏
					console.log(res.windowHeight); // 能够使用的窗口高度，不包含导航栏
					console.log(res.screenWidth); // 屏幕宽度
					console.log(res.windowWidth); //  能够使用的窗口宽度

					// 能够使用的窗口高度，将px转换rpx
					let windowHeight = (res.windowHeight * (750 / res.windowWidth))
					console.log(res.windowWidth, windowHeight)

					this.box_w = res.windowWidth * 2;
					this.box_h = windowHeight;
					
					const randomY = Math.floor(Math.random() * 3) + 24;
					const randomX = Math.floor(Math.random() * 15);
					this.startVector = [randomX, randomY];

					this.rows = this.generateGrids();
					this.createAPlus();
				}
			})
		},
		methods: {
			async clickFn(col) {
				console.log(this.message, this.path.length)
				
				// 当正在运动中，则不允许选择新房间
				if(!isNaN(this.message) && this.path.length && this.message !== (this.path.length - 1)) {
					return uni.showToast({
						icon: 'error',
						title: '正在运动中……'
					});
				}
				
				// 当没有选择房间时，随机初始位置
				if(!this.endVector || !this.endVector.length) {
					this.startVector = [];
					await setAsyncFunWait(200);
					
					console.log("col:", col);
					const randomY = Math.floor(Math.random() * 3) + 24;
					const randomX = Math.floor(Math.random() * 15);
					this.startVector = [randomX, randomY];
				}
				
				let currentArea = '';
				for (let area in this.boxData) {
					console.log("this.boxData[area]:", area)
					for (var i = 0; i < this.boxData[area].length; i++) {
						if(this.boxData[area][i][0] === col.x && this.boxData[area][i][1] === col.y) {
							console.log("area:", area, this.boxData[area][i], [col.x, col.y])
							currentArea = area;
						}
					}
				}
				console.log("currentArea:", currentArea);
				
				if(!currentArea) {
					return uni.showToast({
						icon: 'error',
						title: '请选择正确区域'
					});
				}
				
				uni.showToast({
					icon: 'none',
					title: `您选择了${currentArea}!`
				});
				
				// this.clickCount++;
				// 获取两个格子的间的最短路径
				// if (this.clickCount === 1) {
				// 	this.startVector = [col.x, col.y];
				// } else if (this.clickCount === 2) {
				// 	this.clickCount = 0;
					this.endVector = [col.x, col.y];

					// 直接获取路径展示
					this.path = [];
					this.pathFillColor(APlus.getPath(this.startVector, this.endVector));

					// 预期结果路径与其它分支路径展示
					// this.run({
					//   startVector: this.startVector,
					//   endVector: this.endVector
					// }, ({ path, solved, branchs }) => {
					//   this.branchsFillColor(branchs);
					//   this.pathFillColor(path);
					// });
				// }
			},
			// 生成格子
			generateGrids() {
				const rows = [];
				for (let i = 0; i < this.row; i++) {
					const row = [];
					for (let j = 0; j < this.col; j++) {
						const element = {
							x: j,
							y: i
						};
						element.id = `${j}_${i}`;

						if (i === 0) element.borderTop = `1px solid black`;
						if (j === 0) element.borderLeft = `1px solid black`;

						// 生成障碍物
						// const randomNum = Math.random() * 834819 & 7;
						// if (randomNum > 5) {
						// 	this.obstacles.push([j, i]);
						// 	element.background = '#666';
						// }

						this.obstacles.forEach(item => {
							if (item[0] === j && item[1] === i) {
								element.background = '#f00';
							}
						})


						row.push(element);
					}
					rows.push(row);
				}
				return rows;
			},
			// 创建 APlus 实例
			createAPlus() {
				this.aPlus = APlus.create({
					screenSize: [this.col, this.row],
					obstacles: this.obstacles
				});
			},
			// 路径染色
			pathFillColor(path) {
				if (path.length < 1) {
					this.message = '此路不通，离终点十万八千里 -_-|||!';
					return;
				}
				const rgba = this.ramdomRGBA();
				let count = 0;

				console.log("path:", path)
				this.path = path;

				const loop = (p = path) => {
					const vector = p[count];

					if (!vector) return;

					// const el = this.$refs[`${vector[0]}_${vector[1]}`];
					// el.style.background = rgba;
					this.rows[vector[1]][vector[0]].background = rgba;
					
					// left: col.x * el_w + 'rpx',
					// top: col.y * el_h + 'rpx', 
					this.startVector = [vector[0], vector[1]];

					setTimeout(() => loop(p), 100);
					this.message = count;

					count += 1;
					if (count >= p.length) {
						if (vector[0] !== this.endVector[0] || vector[1] !== this.endVector[1]) {
							setTimeout(() => this.message = '此路不通，要么翻山，要么打洞 -_-|||!');
						}
						return;
					}
				}

				loop();
			},
			// 路径分支集合染色
			branchsFillColor(branchs) {
				if (branchs.length < 1) {
					this.message = '没有任何路径，哪怕原地踏步不会没有路径，你该吃药了 -_-|||!';
					return;
				}
				const colorMap = new Map();
				const len = branchs.length;
				let count = 0;

				// 分支路径色彩映射
				for (let i = 0; i < len; i++) {
					colorMap.set(i, this.ramdomRGBA());
				}

				const loop = (b = branchs) => {
					const bLen = b.length;
					let isComplete = true;

					for (let j = 0; j < bLen; j++) {
						const vector = b[j][count];

						if (vector) {
							isComplete = false;
							// const el = this.$refs[`${vector[0]}_${vector[1]}`];
							// el.style.background = colorMap.get(j);
							// el.textContent = count + 1;
							this.rows[vector[1]][vector[0]].background = colorMap.get(j);
						}
					}
					// this.message = count;
					if (!isComplete && count < 100) {
						count += 1;
						setTimeout(() => loop(b), 100);
					}
				}

				loop();
			},
			ramdomRGBA(opacity = 1) {
				const num = 1 << 10;
				return `rgba(${(Math.random() * num) & 255}, ${(Math.random() * num) & 255}, ${(Math.random() * num) & 255}, ${opacity})`;
			}
		},

	};
</script>

<style lang="scss" scoped>
	.demo-page {
		width: 100vw;
		height: 100vh;
		position: absolute;
		top: 0;
		left: 0;

		view {
			box-sizing: border-box;
		}
	}

	#container {
		position: relative;
		background: transparent;

	}

	#container view {
		position: absolute;
	}

	.cell {
		border: 1px solid black;
		border-width: 0 1px 1px 0;
		position: absolute;
		font-size: 10px;
		color: #FFF;
		cursor: pointer;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>